package com.rimi.bbs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rimi.bbs.bean.Role;
import com.rimi.bbs.bean.User;
import com.rimi.bbs.mapper.UserMapper;
import com.rimi.bbs.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jerry
 * @since 2019-02-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public User login(User user) {
        if(user==null){
            return null;
        }
        return userMapper.selectOne(new QueryWrapper<User>()
                .eq("user_email", user.getUserEmail())
                .eq("user_password",user.getUserPassword()));
    }

    @Override
    public boolean register(User user) {
        //获取当前时间
        user.setUserCreatetime(LocalDateTime.now());
        //默认普通用户
        user.setUserRole(Role.ROLE_USER);
        //密码加密
        String encode = passwordEncoder.encode(user.getPassword());
        user.setUserPassword(encode);
        //密码加密
        int insert = userMapper.insert(user);
        if(insert>0){
            return true;
        }
        return false;
    }

    @Override
    public User getUserByEmailName(String email) {
        if(email==null){
            return null;
        }
        return userMapper.selectOne(new QueryWrapper<User>()
                .eq("user_email", email));
    }

    @Override
    public User getUserByName(String userName) {
        if(userName==null){
            return null;
        }
        return userMapper.selectOne(new QueryWrapper<User>()
                .eq("user_name", userName));
    }

    @Override
    public boolean updateUserPassword(Integer id, String password) {
        int i = userMapper.updateById(new User()
                //用户Id
                .setUserId(id)
                //密码加密
                .setUserPassword(passwordEncoder.encode(password)));
        if(i>0){
            return true;
        }
        return false;
    }

    @Override
    public boolean updateUserByEmail(User user) {
        int num = userMapper.update(user.setUserPassword(passwordEncoder.encode(user.getPassword())), new QueryWrapper<User>().eq("user_email", user.getUserEmail()));
        if(num>0){
            return true;
        }
        return false;
    }

}
